package com.zhaojk.audio.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import com.zhaojk.audio.config.VolcTextConfig;
import com.zhaojk.audio.domain.DTO.WordDefinition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 火山引擎文本大模型服务
 *
 */
@Service
@Slf4j
public class VolcTextServiceImpl {
    @Autowired
    private VolcTextConfig vcTextConfig;
    /**
     * 获取与word相似的答案
     * @param wordDefinition
     * @return
     */
    public List<String> getSimilarPronunciationToWord(WordDefinition wordDefinition) {
        String pos = wordDefinition.getPos();
        String word =  wordDefinition.getLemma();
        String prompt = "与" + word + "发音相似的单词有哪些(不包括"+ word +"本身)？要求：只给出两个结果，结果用json数组给出";
        switch (pos) {
            case "n":
                prompt = "与" + word + "发音相似的单词有哪些(不包括"+ word +"本身)？要求：只给出两个结果，结果用json数组给出";
                break;
            case "x":
                prompt = word + "是题目的答案。给出与" + word + "不同的答案来做选项(不包含" + word + "本身)。要求：1.只给出两种答案，用json数组。2.给出的答案与原答案有明显的区别，答案可用于生成音频来表达意思。";
                break;
            default:
                prompt = "与" + word + "发音相似的单词有哪些(不包括"+ word +"本身)？要求：只给出两个结果，结果用json数组给出";
        }
        String text = chat(prompt);
        // 去掉中括号外的内容
        String jsonString = text.substring(text.indexOf("["), text.indexOf("]")+1);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(jsonString, List.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取与word图片相似的单词列表
     * @param wordDefinition
     * @return
     */
    public List<String> getSimilarPicToWord(WordDefinition wordDefinition){
        String word = wordDefinition.getLemma();
        String pos = wordDefinition.getPos();
        String prompt;
        switch (pos) {
            case "n":
                prompt = "与" + word + "相似的物品(不包含" + word + "本身)。要求：只给出两种结果，用json数组";
                break;
            case "x":
                prompt = word + "是题目的答案。给出与" + word + "不同的答案来做选项(不包含" + word + "本身)。要求：1.只给出两种答案，用json数组。2.给出的答案与原答案有明显的区别，答案可用于生成图片来表达意思。";
                break;
            default:
                prompt = "与" + word + "相似的物品(不包含" + word + "本身)。要求：只给出两种结果，用json数组";
        }
        String text = chat(prompt);
        // 去掉中括号外的内容
        String jsonString = text.substring(text.indexOf("["), text.indexOf("]")+1);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(jsonString, List.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取与word图片相似的单词列表
     * @param word
     * @return
     */
    public List<String> getSimilarPicToWord(String word){
        String prompt = "与" + word + "相似的物品(不包含" + word + "本身)。要求：只给出两种结果，用json数组";
        String text = chat(prompt);
        // 去掉中括号外的内容
        String jsonString = text.substring(text.indexOf("["), text.indexOf("]")+1);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(jsonString, List.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 与文本大模型对话
     * @param prompt 提示词
     * @return
     */
    public String chat(String prompt){
        String apiKey = vcTextConfig.getArkApiKey();
        ArkService service = ArkService.builder().apiKey(apiKey).build();
        log.info("----- standard request -----");
        final List<ChatMessage> messages = new ArrayList<>();
        final ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content("你是豆包，是由字节跳动开发的 AI 人工智能助手").build();
        final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(prompt).build();
        messages.add(systemMessage);
        messages.add(userMessage);
        // 查询Model ID：https://www.volcengine.com/docs/82379/1330310
        // 两种常用模型： doubao-1.5-pro-32k-250115, deepseek-v3-250324
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model("deepseek-v3-250324")
                .messages(messages)
                .build();
        final String[] resultMessage = {""};
        service.createChatCompletion(chatCompletionRequest).getChoices().forEach(choice -> {
            resultMessage[0] = (String) choice.getMessage().getContent();
            log.info("----- 返回结果：" + resultMessage[0]);
        });
        // shutdown service
        service.shutdownExecutor();
        return resultMessage[0];
    }
}
